package com.snakegame.ui;

import com.snakegame.core.GameManager;
import com.snakegame.config.GameState;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 游戏键盘监听器，处理游戏中的键盘输入
 */
public class GameKeyListener extends KeyAdapter {
    private GameManager gameManager;
    
    public GameKeyListener(GameManager gameManager) {
        this.gameManager = gameManager;
    }
    
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        
        // 处理暂停
        if (keyCode == KeyEvent.VK_P) {
            gameManager.togglePause();
            return;
        }
        
        // 如果游戏结束或暂停，不处理方向键
        if (gameManager.isGameOver() || gameManager.isPaused()) {
            return;
        }
        
        // 处理蛇的方向控制
        if (gameManager.getSnakes().size() >= 1) {
            com.snakegame.entity.Snake snake1 = gameManager.getSnakes().get(0);
            switch (keyCode) {
                case KeyEvent.VK_UP:
                    snake1.setDirection(com.snakegame.config.Direction.UP);
                    break;
                case KeyEvent.VK_DOWN:
                    snake1.setDirection(com.snakegame.config.Direction.DOWN);
                    break;
                case KeyEvent.VK_LEFT:
                    snake1.setDirection(com.snakegame.config.Direction.LEFT);
                    break;
                case KeyEvent.VK_RIGHT:
                    snake1.setDirection(com.snakegame.config.Direction.RIGHT);
                    break;
            }
        }
        
        // 双人模式下处理第二条蛇的控制
        if (gameManager.getSnakes().size() >= 2) {
            com.snakegame.entity.Snake snake2 = gameManager.getSnakes().get(1);
            switch (keyCode) {
                case KeyEvent.VK_W:
                    snake2.setDirection(com.snakegame.config.Direction.UP);
                    break;
                case KeyEvent.VK_S:
                    snake2.setDirection(com.snakegame.config.Direction.DOWN);
                    break;
                case KeyEvent.VK_A:
                    snake2.setDirection(com.snakegame.config.Direction.LEFT);
                    break;
                case KeyEvent.VK_D:
                    snake2.setDirection(com.snakegame.config.Direction.RIGHT);
                    break;
            }
        }
    }
}    